//================ 我是地址新增页面 ====================
import React, { useState, ChangeEvent, KeyboardEvent } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/newadd.module.css";
import leftImg from "../img/left.png";
import { address_save } from "../api/address"; //新增地址接口
type FormField = "name" | "tel" | "addres" | "address";
type FormData = {
  [key in FormField]: string;
} & {
  isDefault: boolean;
};

const fieldLabels: Record<FormField, string> = {
  name: "收货人:",
  tel: "手机号码:",
  addres: "所在地区:",
  address: "详细地址:",
};

const fieldPlaceholders: Record<FormField, string> = {
  name: "请输入收货人姓名",
  tel: "请输入收货人手机号",
  addres: "请输入收货人地址",
  address: "街道,楼道号",
};

const NewaddPage = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState<FormData>({
    name: "",
    tel: "",
    addres: "",
    address: "",
    isDefault: false,
  });

  const [hintMessage, setHintMessage] = useState("");
  const [showHint, setShowHint] = useState(false);

  const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { id, value } = e.target;
    if (id === "tel") {
      // 使用正则表达式过滤汉字、字母和标点符号
      const validValue = value.replace(/[\u4e00-\u9fa5a-zA-Z\W_]/g, "");
      setFormData((prev) => ({
        ...prev,
        [id as FormField]: validValue,
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        [id as FormField]: value,
      }));
    }
  };

  const handleSwitchChange = () => {
    setFormData((prev) => ({ ...prev, isDefault: !prev.isDefault }));
  };

  const handleKeyPress = (e: KeyboardEvent<HTMLImageElement>) => {
    if (e.key === "Enter" || e.key === " ") {
      navigate(-1);
    }
  };

  const handleSwitchKeyPress = (e: KeyboardEvent<HTMLDivElement>) => {
    if (e.key === "Enter" || e.key === " ") {
      handleSwitchChange();
    }
  };

  const showHintMessage = (message: string) => {
    setHintMessage(message);
    setShowHint(true);
    setTimeout(() => setShowHint(false), 2000);
  };
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");
  const handleSubmit = async () => {
    if (
      Object.values(formData).some(
        (value) => typeof value === "string" && !value
      )
    ) {
      showHintMessage("输入框不得为空！");
      return;
    }
    //============= 请求地址新增接口================
    try {
      const response = await address_save({
        body: JSON.stringify({
          uid: Number(user.data.id), // 确保 uid 是数字类型
          name: formData.name,
          tel: formData.tel,
          address: formData.addres,
          desc: formData.address,
          default: formData.isDefault == true ? 1 : 0,
        }),
      });
      console.log(formData, "保存地址信息");
      console.log(response, "保存地址信息");
      if (response.data.code === 1) {
        showHintMessage("添加成功！");
        setTimeout(() => navigate("/address"), 1000);
      }
    } catch (error) {
      console.error("保存失败:", error);
      showHintMessage("保存失败，请重试");
    }
  };
  const goBack = () => navigate(-1);
  return (
    <div className={styles.container}>
      {showHint && (
        <div role="alert" className={styles.hintContainer}>
          <div className={styles.hint}>{hintMessage}</div>
        </div>
      )}

      <div className={styles.top}>
        <div className={styles.top}>
          <img onClick={goBack} src={leftImg} alt="返回" />
          <b>地址添加</b>
        </div>
      </div>
      <div style={{ height: "6px" }}></div>
      <div className={styles.content}>
        {(Object.keys(fieldLabels) as FormField[]).map((field, index) => (
          <React.Fragment key={field}>
            <div className={styles.contentItem}>
              <label htmlFor={field} className={styles.inputLabel}>
                {fieldLabels[field]}
              </label>
              <input
                id={field}
                type={field === "tel" ? "tel" : "text"}
                placeholder={fieldPlaceholders[field]}
                value={formData[field]}
                onChange={handleInputChange}
                aria-required="true"
                className={styles.inputField}
              />
            </div>
            {index < 3 && <div className={styles.divider} />}
          </React.Fragment>
        ))}
      </div>

      <div className={styles.defaultAddress}>
        <span id="defaultLabel">设为默认地址</span>
        <div
          role="switch"
          aria-labelledby="defaultLabel"
          aria-checked={formData.isDefault ? "true" : "false"}
          tabIndex={0}
          onClick={handleSwitchChange}
          onKeyDown={handleSwitchKeyPress}
          className={styles.switchContainer}
        >
          <div className={styles.switchTrack}>
            <div
              className={`${styles.switchThumb} ${
                formData.isDefault ? styles.switchChecked : ""
              }`}
            />
          </div>
        </div>
      </div>

      <button
        className={styles.saveButton}
        onClick={handleSubmit}
        type="button"
        aria-label="保存收货地址信息"
      >
        保存
      </button>
    </div>
  );
};

export default NewaddPage;
